<script setup>
	import {
		onMounted,
		ref,
		watch
	} from "vue";
	import {
		onUnload,
		onLoad
	} from "@dcloudio/uni-app";
	import {
		useUserStore
	} from "../../store/user";
	import { useRegister } from '../../hooks/login'
	import { uniFetch } from '../../api/uni-fetch';
  import LoadingUnit from '@/components/LoadingUnit/LoadingUnit.vue';
  import LoadingSuccess from '@/components/LoadingSuccess/LoadingSuccess.vue';

	const userStore = useUserStore();

	const errorPopup = ref(null);
	const create = ref(false);
	onMounted(() => {
		watch(
			() => userStore.userInfo,
			(newValue) => {
				console.log(newValue, "监听器==>用户信息");
				if (!newValue) {
					openLoginPopup();
					return;
				} else if (newValue && !userStore.userInfo.phone) {
					openPhonePopup();
					return;
				} else {
					loginPopup.value.close();
					phonePopup.value.close();
					if (create.value) return;
					createOrder();
					return;
				}
			}, {
				immediate: true,
				deep: true,
			}
		);
	});

	onLoad((device) => {
		// // #ifdef MP-ALIPAY
		// uni.setStorageSync('isProcessingQr', true)
		// // #endif
		// console.log(device, 'device');
		if (device.machineId) {
			deviceId.value = device.machineId;
		} else if (device.q) {
			const URLres = decodeURIComponent(device.q);
			deviceId.value = URLres.split("id=")[1];
		}
	});

	const deviceId = ref(null);
	const timer1 = ref(null);
	const orderInfo = ref(null);
	const statusText = ref("加载中");
	const isLoading = ref(true);

  // 订单创建
	async function createOrder() {
		create.value = true;
		const orderRes = await uniFetch.post(
			"/order/create?time=" + new Date().getTime(), {
				device: deviceId.value,
				needUserConfirm: 1,
			}
		);
		console.log(orderRes, "创建订单");
		if (orderRes.code === 10000) {
			orderInfo.value = orderRes.data;
			payScoreConfirm(orderRes.data.fupin_send_msg);
		} else {
			statusText.value = orderRes.msg;
			errorPopup.value.open("center");
			
			// // #ifdef MP-ALIPAY
			// if (orderRes.msg == '用户未签约') {
			// 	timer1.value = setTimeout(() => {
			// 		uni.redirectTo({
			// 			url: "/skgPagesA/payPos/payPos?machineId=" + deviceId.value
			// 		})
			// 	}, 2500);
			// }
			// // #endif

			timer1.value = setTimeout(() => {
				uni.switchTab({
						url: "/pages/index/index"
				});
			}, 2500);
		}
	}

	async function payScoreConfirm(extraData) {
		// #ifdef MP-WEIXIN
		if (wx.openBusinessView) {
			//微信支付分，走“需确认支付”流程
			wx.openBusinessView({
				businessType: "wxpayScoreUse",
				extraData,
				success: (res) => {
					if (res && res.extraData && res.extraData.query_id) {
						console.log("购物流程,授权支付分");
						isLoading.value = false;
						timer1.value = setTimeout(() => {
							uni.redirectTo({
								url: "/pages/openDoor/openDoor?id=" + orderInfo.value.id,
							});
						}, 1500);
					} else {
						uni.showToast({
							title: "请授权支付分",
							icon: "none",
						});
						payScoreConfirm(extraData);
					}
				},
				fail: (err) => {
					console.log("用户微信支付分确认失败", err);
					uni.showToast({
						title: err.errMsg,
						icon: "none",
						duration: 3000,
					});
					timer1.value = setTimeout(() => {
						uni.switchTab({
								url: "/pages/index/index"
						});
					}, 3500);
				},
			});
		} else {
			uni.showToast({
				title: "您的微信版本过低，请升级后再试",
				icon: "none",
			});
			timer1.value = setTimeout(() => {
				uni.switchTab({
						url: "/pages/index/index"
				});
			}, 2000);
		}
		// #endif

		// // #ifdef MP-ALIPAY
		// console.log("支付宝创建订单结束");
		// isLoading.value = false;
		// timer1.value = setTimeout(() => {
		// 	uni.redirectTo({
		// 		url: "/pages/openDoor/openDoor?id=" + orderInfo.value.id,
		// 	});
		// }, 1500);
		// // #endif
	}

	// 登录授权
	const loginPopup = ref(null);
	function openLoginPopup() {
		loginPopup.value.open("bottom");
	}

	// 手机号授权
	const phonePopup = ref(null);
	function openPhonePopup() {
		phonePopup.value.open("bottom");
	}

	const isPhone = ref(false);
	async function getPhoneNumber(e) {
		if (e.detail.errno === 1400001) {
			isPhone.value = true;
			userStore.userInfo.phone = "123";
			phonePopup.value.close();
		} else {
			const res = await uniFetch.get("/user/phone", e.detail);
			if (res.code === 10000) {
				userStore.userInfo = res.data.user;
				isPhone.value = true;
			} else {
				phonePopup.value.close();
				if (create.value) return;
				createOrder();
			}
		}
	}

	// 登录按钮
	async function userLogin(loginRes) {
		await useRegister()
	}

	// 导航栏  信息获取
	const paddingHeight = ref(0);
	const navbarHeight = ref(0);
	const lineHeight = ref(0);
	const safeBottom = ref(0);
	uni.getSystemInfo({
		success: function(res) {
			const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
			paddingHeight.value = menuButtonInfo.top;
			navbarHeight.value = res.statusBarHeight;
			safeBottom.value = res.safeAreaInsets.bottom;
			lineHeight.value =
				res.statusBarHeight - (res.statusBarHeight - menuButtonInfo.height);
		},
		fail: (err) => {
			console.log(err);
		},
	});
	// 清除定时器
	onUnload(() => {
		uni.$emit("play");
		clearTimeout(timer1.value);
	});

	function closePhonePopup() {
		uni.showModal({
			content: "确认取消手机号授权?",
			success: (res) => {
				if (res.confirm) {
					phonePopup.value.close();
					if (create.value) return;
					createOrder();
				}
			},
		});
	}

	function closeLoginPopup() {
		uni.showModal({
			content: "确认取消登录?",
			success: (res) => {
				if (res.confirm) {
					loginPopup.value.close();
					uni.switchTab({
						url: "/pages/index/index"
					});
				}
			},
		});
	}
</script>

<template>
	<view>
		<cover-view class="navigationBarTitle" :style="{
        paddingTop: paddingHeight + 'px',
        height: navbarHeight + 'px',
        lineHeight: lineHeight + 'px',
        fontSize: lineHeight - 12 + 'px',
      }">
			<navigator url="/pages/index/index" open-type="reLaunch" style="position: absolute; left: 25rpx">
				<!-- #ifdef MP-WEIXIN -->
				<uni-icons size="30" color="color: #fefefe;" type="home-filled"></uni-icons>
				<!-- #endif -->
			</navigator>
			<view class="title">授权使用</view>
		</cover-view>
		<view class="open-door" :style="{ paddingTop: paddingHeight + lineHeight + navbarHeight + 'px' }">
			<view class="image" style="background-image: url(https://dmg.nex-i.cn/res/wx/pic1.png)"></view>
			<view class="welcome">欢迎使用</view>
			<view class="welcome-titile">智能售货机</view>
			<view style="height: 400rpx; padding: 100rpx">
				<LoadingUnit :isBgc="false" v-if="isLoading"></LoadingUnit>
				<LoadingSuccess v-else>授权成功</LoadingSuccess>
			</view>
		</view>

		<uni-popup ref="errorPopup" type="center">
			<view class="error">
				<view class="bgc">
					<image src="/static/images/error.png" mode="widthFix"></image>
					<view class="text">{{ statusText }}</view>
				</view>
			</view>
		</uni-popup>

		<!--登录授权弹框 -->
		<uni-popup ref="loginPopup" type="bottom" :safe-area="true" :is-mask-click="false">
			<view class="login-form">
				<uni-icons @click="closeLoginPopup" type="close" color="#949494" size="30"
					style="position: absolute; right: 30rpx"></uni-icons>
				<view class="login-title">
					<image src="/static/logo.png"></image>
					<view class="welcome">欢迎使用智能售卖柜</view>
					<view class="tips">登录后，您将可以享受更多功能</view>
				</view>
				<LoadingUnit></LoadingUnit>
				<view class="login-button">
					<button class="login" @click="userLogin">
						<uni-icons type="weixin" color="#fefefe" size="30"></uni-icons>
						授权登录
					</button>
				</view>
			</view>
		</uni-popup>

		<!--手机号授权弹框 -->
		<uni-popup ref="phonePopup" mask-background-color="ffffff00" type="bottom" :safe-area="true"
			:is-mask-click="false">
			<view class="phone-form" :style="{
          paddingBottom: safeBottom + 'px',
          marginBottom: -safeBottom + 'px',
        }">
				<uni-icons @click="closePhonePopup" type="close" color="#949494" size="30"
					style="position: absolute; right: 30rpx"></uni-icons>
				<view class="phone-title">
					<image src="/static/logo.png"></image>
					<view class="welcome">请您授权手机号</view>
					<view class="tips">用于订单绑定和售后服务，请您放心授权</view>
				</view>
				<view>
					<LoadingUnit></LoadingUnit>
					<LoadingSuccess v-if="isPhone">获取成功</LoadingSuccess>
					<view class="phone-button">
						<button :phone-number-no-quota-toast="false" open-type="getPhoneNumber" class="phone"
							@getphonenumber="getPhoneNumber">
							授权手机号码
						</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
	<!-- <ws-wx-privacy id="privacy-popup"></ws-wx-privacy> -->
</template>

<style lang="scss">
	view {
		box-sizing: border-box;
	}
	.navigationBarTitle {
		position: fixed;
		top: 0;
		z-index: 999;
		// background-color: #ffffff11;
		background-color: #0f51cc;
		color: #fefefe;
		width: 100%;
		backdrop-filter: blur(5rpx);
		box-shadow: 0 10px 20px 0px rgba(184, 184, 184, 0.1);

		.title {
			text-align: center;
		}
	}

	.open-door {
		padding: 20rpx 20rpx 50rpx;
		height: 100vh;
		// background-image: url('/static/images/bgc1.png');
		background-size: 100%;
		background-repeat: no-repeat;
		background-color: #edf0f0;

		image {
			width: 200rpx;
			height: 200rpx;
			border-radius: 100%;
			display: block;
			margin: 0 auto 80rpx;
		}

		.image {
			width: 100%;
			height: 320rpx;
			background-size: 100%;
			background-repeat: no-repeat;
			background-color: #edf0f0;
			border-radius: 30rpx;
		}

		.welcome {
			padding-top: 30rpx;
			color: #717171;
			// font-weight: 700;
			font-size: 40rpx;
			text-align: center;
			line-height: 75rpx;
		}

		.welcome-titile {
			// color: #fefefe;
			line-height: 75rpx;
			text-align: center;
			letter-spacing: 5rpx;
			font-size: 50rpx;
			font-weight: 700;
			color: #f08300;
		}

		// .container {
		// 	margin: 100rpx auto 0;
		// 	width: fit-content;
		// 	height: 150rpx;
		// 	position: relative;
		// 	display: flex;
		// 	align-items: center;
		// 	justify-content: center;
		// 	// backdrop-filter: blur(5rpx);
		// 	font-weight: bold;
		// 	letter-spacing: 5rpx;
		// 	// border-bottom: 5rpx solid #8c7e80;
		// 	text {
		// 		position: relative;
		// 		top: 20rpx;
		// 		display: inline-block;
		// 		animation: bounce 1s ease infinite alternate;
		// 		font-family: 'Impact', sans-serif;
		// 		font-size: 80rpx;
		// 		text-shadow: 0 1px 0 #5967ff, 0 2px 0 #5967ff, 0 3px 0 #5967ff, 0 4px 0 #5967ff, 0 5px 0 #5967ff, 0 6px 0 transparent, 0 7px 0 transparent, 0 8px 0 transparent,
		// 			0 9px 0 transparent, 0 10px 10px rgba(0, 0, 0, 0.4);
		// 	}
		// 	text:nth-child(1n + 0) {
		// 		color: var(--color);
		// 		animation-delay: var(--delay);
		// 	}
		// 	@keyframes bounce {
		// 		50% {
		// 			top: 20px;
		// 			text-shadow: 0 1px 0 #5967ff, 0 2px 0 #5967ff, 0 3px 0 #5967ff, 0 4px 0 #5967ff, 0 5px 0 #5967ff, 0 6px 0 #5967ff, 0 7px 0 #5967ff, 0 8px 0 #5967ff, 0 9px 0 #5967ff,
		// 				0 50px 25px rgba(0, 0, 0, 0.2);
		// 		}
		// 		100% {
		// 			top: 20px;
		// 			text-shadow: 0 1px 0 #5967ff, 0 2px 0 #5967ff, 0 3px 0 #5967ff, 0 4px 0 #5967ff, 0 5px 0 #5967ff, 0 6px 0 #5967ff, 0 7px 0 #5967ff, 0 8px 0 #5967ff, 0 9px 0 #5967ff,
		// 				0 50px 25px rgba(0, 0, 0, 0.2);
		// 		}
		// 	}
		// }
	}

	.error .bgc {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		width: 350rpx;
		height: 350rpx;
		border-radius: 30rpx;

		image {
			width: 150rpx;
			height: 150rpx;
		}

		.text {
			padding-top: 30rpx;
			color: #fff;
			font-size: 35rpx;
			text-align: center;
		}
	}

	.login-form {
		position: relative;
		padding: 40rpx 30rpx 150rpx;
		background-color: #fefefe;
		border-radius: 40rpx 40rpx 0 0;

		.login-title {
			image {
				display: block;
				margin: 30rpx auto 30rpx;
				width: 130rpx;
				height: 130rpx;
				border-radius: 50%;
				vertical-align: middle;
			}

			.welcome {
				text-align: center;
				font-size: 40rpx;
				color: #000;
			}

			.tips {
				font-size: 25rpx;
				padding-top: 20rpx;
				text-align: center;
				color: rgba(107, 114, 128, 1);
			}
		}

		.login-button {
			.login {
				margin: 0rpx auto 50rpx;
				height: 48px;
				opacity: 1;
				border-radius: 6px;
				background: #32af5a;
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 12px 18.13px 12px 17.88px;
				width: 400rpx;
				color: #fefefe;
			}
		}
	}

	.phone-form {
		position: relative;
		padding: 20rpx 60rpx 30rpx;
		background-color: #fefefe;
		border-radius: 40rpx;
		// background-color: pink;
		height: 50vh;

		.phone-title {
			margin-bottom: -40rpx;

			image {
				display: block;
				margin: 30rpx auto 30rpx;
				width: 130rpx;
				height: 130rpx;
				border-radius: 50%;
				vertical-align: middle;
			}

			.welcome {
				text-align: center;
				font-size: 40rpx;
				color: #000;
			}

			.tips {
				font-size: 25rpx;
				padding-top: 20rpx;
				text-align: center;
				color: rgba(107, 114, 128, 1);
			}
		}

		.phone-button {
			margin-top: -40rpx;

			.phone {
				margin: 10rpx 0 30rpx;
				height: 48px;
				border-radius: 6px;
				background: #32af5a;
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 12px 18.13px 12px 17.88px;
				color: #fefefe;
			}
		}
	}
</style>